<template>
  <div id="c2cChart"></div>
</template>

<script>
import Utils from '@/utils/Utils.js'
import Echarts from '@/libs/echarts.min.js'
import commonFilter from '@/filters/common.js'

export default {
  props: [
    'lang',
    'pair'
  ],
  data () {
    return {
      timer: null,
      intervals: {
        VHKDCNY: 1,
        VHKDVND: 1,
        BTCCNY: 5
      }
    }
  },
  computed: {
    minute () {
      if (this.pair.coinCode === 'BTC' && this.pair.currencyCode === 'CNY') return 15
      return 5
    }
  },
  watch: {
    pair: {
      handler () {
        this.getHistoryMarketData()
        this.setInterval()
      },
      deep: true
    }
  },
  components: {

  },
  methods: {
    getHours (times, prices) {
      let hourReg = /:0{1,2}$/
      let hours = []

      // 筛选区间整点
      let gap = 6 - 0 // 0   6    12    18    0
      times.forEach((item, index) => {
        let hour = parseInt(item.split(':')[0])
        if (hourReg.test(item) && hour % gap === 0) {
          hours.push({
            time: item,
            index,
            hour: hour
          })
        }
      })

      // 若第一个整点与最后一个整点相同，则最后一个区间删除显示为空

      let currentTime = Utils.formatDate(new Date(), 'hh:mm')
      let currentHour = currentTime.split(':')[0]

      // 若第一区整时与最后区整时处于同一整时区，则前面第一个整时区删除
      if (Math.floor(parseFloat(currentHour) / gap) === Math.floor(parseFloat(times[0].split(':')[0]) / gap) && hours.length) {
        let clearStartIndex = hours[0].index // 取倒数第二个区间整点index开始向后删除
        // let clearEndIndex = hours[1].index - clearStartIndex
        times.splice(0, clearStartIndex)
        prices.splice(0, clearStartIndex)
        times.unshift(times[0]) // 最前面加一条才会显示
        prices.unshift(prices[0])
      }

      return {
        times,
        prices
      }
    },
    getHistoryMarketData () { // 指数
      this.$host2.post('ExchangeIndex/GetIndexDataList', {
        minute: this.minute,
        latestHour: 25,
        sourceCode: this.pair.coinCode,
        targetCode: this.pair.currencyCode
      }, {
        ignorableCodes: '41000',
        // mock: 'ctcIndex'
      }).then((res) => {
        // let allHour = 25
        if (res.isOk) {
          let list = (res.Data && res.Data.DateList) || []

          if (!list.length) return

          // list = list.slice(-24)
          let prices = []
          let times = []

          for (let i = 0; i < list.length; i++) {
            prices.push(commonFilter.fillDecimal(list[i].Price, this.pair.cyPrec))
            let data = Utils.fixNewDateStringForIE(list[i].Time, 'yyyy/MM/dd hh:mm:ss')
            times.push(Utils.formatDate(new Date(data), 'hh:mm'))
          }

          let tmp = this.getHours(times, prices)
          times = tmp.times
          prices = tmp.prices

          let ary = prices
          let maxN = Math.max.apply(null, ary) // * (1 + 0.001)
          let minN = Math.min.apply(null, ary) // * (1 - 0.00001)
          let margin = (maxN - minN) * (1 / 10)
          maxN += margin
          minN -= (margin * 3)

          this.indexData(maxN, minN, prices, times)
        }
      })
    },
    indexData (maxN, minN, prices, times) {
      let that = this
      let dom = document.getElementById('c2cChart')
      let myChart = Echarts.init(dom)
      let option = null
      let fontColor = '#c5c5c5'
      let interval = (maxN - minN) / 4

      // 应付一直没变的情况
      // 当最大值和最小值一样时即这里计算出来的最终结果会是0，会导致y轴没有数据，所以随便给个1
      if (!interval) {
        interval = 1 / Math.pow(10, this.pair.cyPrec)
        maxN += interval * 1
        minN -= interval * 3
      }

      option = {
        animation: false,
        grid: {
          show: false,
          left: 76,
          right: 20,
          bottom: 50,
          top: 6
        },
        xAxis: {
          axisTick: {
            show: false
          },
          axisLabel: {
            color: fontColor,
            fontSize: 12,
            padding: [4, 0, 0, 0],
            align: 'center',
            interval: 0,
            formatter (value, index) {
              // 筛选区间整点
              let hourReg = /:0{1,2}$/
              let hour = parseInt(value.split(':')[0])
              let gap = 6

              if (!hourReg.test(value) || hour % gap !== 0) return ''

              return value
            }
          },
          type: 'category',
          boundaryGap: false,
          data: times
        },
        yAxis: {
          show: true,
          boundaryGap: false,
          type: 'value',
          axisLabel: {
            fontSize: 10,
            color: fontColor,
            formatter (value, index) {
              return commonFilter.fillDecimal(value, that.pair.cyPrec)
            }
          },
          splitLine: {
            show: false
          },
          interval: interval,
          max: maxN, // y轴最大值
          min: minN
        },
        tooltip: {
          axisPointer: {
            type: 'none' // 不显示指示器，即竖线
          },
          trigger: 'axis', // item浮动框在点上悬浮，axis是一根线
          // position (pos, params, dom, rect, size) {
          //   return obj
          // },
          backgroundColor: '#233242',
          borderWidth: 1,
          borderColor: '#4592DF',
          borderRadius: 0,
          textStyle: {
            fontSize: 12
          },
          // formatter: '{b0}<br>{c0}'
          formatter (params, ticket, callback) {
            let time = params[0].axisValue  // 若为trigger: 'item'，params不是数组
            let val = params[0].data
            return (time || val) ? time + '<br>' + val : null
          }
        },
        series: {
          name: '',
          type: 'line',
          smooth: true,
          data: prices,
          showSymbol: false, // false表示只有在hover显示
          symbolSize: (value, params) => {
            return 5
          },
          itemStyle: {
            borderWidth: 1,
            color: '#2e7fcf',
            emphasis: {
              borderWidth: 6,
              borderColor: 'rgba(46, 127, 207, 0.4)',
              color: '#2e7fcf'
            }
          },
          lineStyle: {
            color: '#4592df',
            width: 1
          },
          areaStyle: {
            color: '#323a45'
          }
        }
      }
      if (option && typeof option === 'object') {
        myChart.setOption(option, true)
      }
      window.addEventListener('resize', myChart.resize)
    },
    setInterval () {
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.getHistoryMarketData()
      }, 1000 * 60 * (this.intervals[(this.pair.coinCode + this.pair.currencyCode).toUpperCase()] || 1)) // 每1分钟刷新一次
    }
  },
  mounted () {

  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
}
</script>
<style lang="less">
@import './../css/common.less';

#c2cChart {
  width:100%; height: 400px; position: absolute; bottom:0
}
</style>
